﻿using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;
using System.Diagnostics.CodeAnalysis;
using TrackSystem.Entities.Dtos.Channel;
using TrackSystem.Entities.Dtos.Sensor;
using TrackSystem.Entities.Extensions;
using TrackSystem.UI.Server.HttpRepository.Channel;
using TrackSystem.UI.Server.HttpRepository.Sensor;

namespace TrackSystem.UI.Server.Units
{
    public partial class SensorForUpdate
    {
        [Parameter]
        public SensorWithChannelDto Sensor { get; set; } = new SensorWithChannelDto();

        private ChannelDto Chn { get; set; }

        private ProtocolParams _ptlParams;

        [Inject]
        public ISensorHttpRepository? repo { get; set; }

        [Inject]
        public IChannelHttpRepository? ChnRepo { get; set; }

        [Inject]
        [NotNull]
        private ToastService? ToastService { get; set; }

        private List<SelectedItem> lstStation = new List<SelectedItem>();

        protected override async Task OnInitializedAsync()
        {
            if (repo == null || ChnRepo == null)
            {
                await ToastService.Error("传感器列表", "数据库未初始化");
                return;
            }

            // 初始化数据
            var items = await ChnRepo.GetAll();
            lstStation = items.Select(c => new SelectedItem(c.Id.ToString(), c.Name)).ToList();

            Chn = Sensor.Channel ??= new ChannelDto();
            ProtocolDefine.Params.TryGetValue(Chn?.Protocol ?? ProtocolEnum.Modbus, out _ptlParams);

            // 初始化数据
            await base.OnInitializedAsync();
        }

        private async Task OnPtlChanged(SelectedItem item)
        {
            if (ChnRepo == null)
            {
                await ToastService.Error("传感器列表", "数据库未初始化");
                return;
            }

            var channels = await ChnRepo.GetAll();
            Chn = channels.FirstOrDefault(c => c.Id.ToString() == item.Value) ?? new ChannelDto();
            ProtocolDefine.Params.TryGetValue(Chn?.Protocol ?? ProtocolEnum.Modbus, out _ptlParams);

            Sensor.channelID = Chn?.Id ?? 0;
            Sensor.Channel = Chn;

            StateHasChanged();
        }
    }
}
